/*
 * @Author: your name
 * @Date: 2020-11-22 15:28:22
 * @LastEditTime: 2020-12-13 12:33:40
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \wechat-server\src\routes\weibo\hotItem.js
 */

import Router from "koa-router";
import axios from "axios";

const router = Router();

const getCookie = () => {
  return axios
    .get("https://xueqiu.com/", {
      withCredentials: true,
    })
    .then((res) => {
      if (res.headers["set-cookie"]) {
        return res.headers["set-cookie"];
      }
      console.log("获取cookie失败");
      return null;
    })
    .catch((err) => {
      console.log("获取cookie失败", err);
    });
};

const getListData = (cookie, maxId) => {
  return axios
    .get(
      `https://xueqiu.com/statuses/livenews/list.json?since_id=-1&max_id=${maxId}&count=15`,
      {
        headers: {
          Accept: "application/json",
          "Accept-Encoding": "gzip",
          "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36",
          Cookie: cookie,
        },
      }
    )
    .then((res) => {
      return res.data;
    })
    .catch((err) => {
      console.log("获取雪球数据失败：", err);
    });
};

router.get("/xueqiu/hotList/:maxid", async (ctx, next) => {
  let cookie = await getCookie();
  let maxId = ctx.params["maxid"];
  if (cookie instanceof Array) {
    cookie = cookie.join(";");
  }
  let data = await getListData(cookie, maxId);
  ctx.body = data;
});

export default router;
